package edu.jmu.myshop.commons.service.imlp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.jmu.myshop.commons.dto.AbstractBaseDomain;
import edu.jmu.myshop.commons.service.BaseCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.MyMapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.Date;

/**
 * @author Wen
 */
public class BaseCrudServiceImpl<T extends AbstractBaseDomain, M extends MyMapper<T>> implements BaseCrudService<T> {

    @Autowired
    protected M mapper;

    private Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    @Override
    public boolean unique(String property, String value) {
        Example example = new Example(entityClass);
        example.createCriteria().andEqualTo(property, value);
        int result = mapper.selectCountByExample(example);
        return result <= 0;
    }

    @Override
    public T save(T domain) {
        int result =0;
        Date date = new Date();
        domain.setUpdated(date);
        if (domain.getId()==null){
            domain.setCreated(date);
            result = mapper.insertUseGeneratedKeys(domain);

        }else {
            result = mapper.updateByPrimaryKey(domain);
        }
        if (result>0){
            return domain;
        }
        return null;
    }

    @Override
    public PageInfo<T> page(T domain, int pageNum, int pageSize) {
        Example example = new Example(entityClass);
        example.createCriteria().andEqualTo(domain);

        PageHelper.startPage(pageNum,pageSize);
        PageInfo<T> pageInfo= new PageInfo<>(mapper.selectByExample(example));

        return pageInfo;
    }
}